package com.iye.puretennis.fragment;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.activity.MainTabsActivity;
import com.iye.puretennis.activity.ProfileActivity;
import com.iye.puretennis.custom.CustomDatePickerDialog;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.domain.News;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserDetail;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.pulltorefresh.library.PullToRefreshBase;
import com.iye.puretennis.pulltorefresh.library.PullToRefreshListView;
import com.iye.puretennis.utils.TimeUtils;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/26
 * Time: 11:49
 */
public class UserDetailFragment extends TabFragment {

    public static String TAG = "user_detail";

    private HuaWenHuPoTextView signInView;

    private HuaWenHuPoTextView playYearView;

    private HuaWenHuPoTextView pointView;

    private HuaWenHuPoTextView qianDaoDaysView;

    private PullToRefreshListView newsListView;

    private int year;

    private int month;

    private int currentPoint = 0;

    private int qianDaoDays;

    private NewsAdapter newsAdapter;

    private LinkedList<News> news = new LinkedList<News>();

    private String updateTo = "";


    @Override
    public void onCustomCreateView(LayoutInflater inflater) {

        signInView = (HuaWenHuPoTextView) mainView.findViewById(R.id.sign_in);

        playYearView = (HuaWenHuPoTextView) mainView.findViewById(R.id.play_year);

        pointView = (HuaWenHuPoTextView) mainView.findViewById(R.id.point);

        qianDaoDaysView = (HuaWenHuPoTextView) mainView.findViewById(R.id.qiandao_days);
        newsListView = (PullToRefreshListView) mainView.findViewById(R.id.news_list);
        newsAdapter = new NewsAdapter(fragmentActivity, R.layout.news_item);

        newsListView.setAdapter(newsAdapter);
        newsListView.setLongClickable(true);

        newsListView.setMode(PullToRefreshBase.Mode.BOTH);
        newsListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadNews(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadNews(false);
            }
        });

        ImageButton actionButton = (ImageButton) mainView.findViewById(R.id.action_button);

        actionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupMenu(view, R.menu.userinfo_logout_menu, new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        if (menuItem.getItemId() == R.id.logout_menu) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    MainTabsActivity activity = (MainTabsActivity) getActivity();
                                    activity.logout();
                                }
                            }).start();
                        } else {
                            Intent intent = new Intent(getActivity(), ProfileActivity.class);
                            startActivity(intent);
                        }
                        return true;
                    }
                });
            }
        });

        render();

    }


    private DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {

        private boolean sendRequest = true;

        @Override
        public void onDateSet(DatePicker view, int cYear, int monthOfYear, int dayOfMonth) {

            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            year = cYear;

            month = monthOfYear;

            //更新日期
            if (sendRequest) {
                updateDate();

            }

            sendRequest = !sendRequest;

        }

        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate() {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject paramJson = new JSONObject();
                    try {
                        paramJson.put("playSince", year + "-" + TimeUtils.formatTime(month + 1));
                        StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                        String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.UPDATE_PLAYER_SINCE), token.getToken(), paramEntity);
                        if (!Constant.RESPONSE_BADLY.equals(result)) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //在TextView上显示日期
                                    playYearView.setText(Constant.PLAY_YEAR + TimeUtils.getPlayYear(year, month + 1));
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    };


    @Override
    public int getViewId() {
        return R.layout.user_detail;
    }

    @Override
    public int getSourceId() {
        return R.id.user_detail;
    }

    @Override
    public void updateUI() {
        if (updateTo.equals("")) {
            loadNews(true);
        }
    }

    @Override
    public boolean isParent() {
        return true;
    }

    private void render() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                final UserDetail userDetail = ServerAccessHelper.loadUserDetail(token.getToken());
                if (userDetail != null) {

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ImageView imageView = (ImageView) mainView.findViewById(R.id.user_photo);

                            String guid = userDetail.getGuid();
                            loadUserImage(guid, imageView);
                            HuaWenHuPoTextView usernameView = (HuaWenHuPoTextView) mainView.findViewById(R.id.username);
                            usernameView.setText(userDetail.getNickname(token.getGuid()));
                            Calendar calendar = Calendar.getInstance();
                            year = userDetail.getYear() == 0 ? calendar.get(Calendar.YEAR) : userDetail.getYear();
                            month = userDetail.getMonth() == 0 ? calendar.get(Calendar.MONTH) : userDetail.getMonth();
                            playYearView.setText(Constant.PLAY_YEAR + userDetail.getPlayYear());
                            playYearView.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {

                                    //创建DatePickerDialog对象
                                    CustomDatePickerDialog dpd = new CustomDatePickerDialog(getActivity(), dateListener, year, month, 1);
                                    dpd.setPermanentTitle(getString(R.string.start_play_time));
                                    DatePicker datePicker = dpd.getDatePicker();
                                    View childAt = ((ViewGroup) datePicker.getChildAt(0)).getChildAt(0);
                                    ((ViewGroup) childAt).getChildAt(2).setVisibility(View.GONE);
                                    datePicker.setMaxDate(new Date().getTime());
                                    dpd.show();//显示DatePickerDialog组件
                                }
                            });

                            currentPoint = userDetail.getAccumulatedPoints();
                            pointView.setText(Constant.POINT + currentPoint);
                            final boolean signIn = userDetail.isCanQianDao();
                            signInView.setTextColor(signIn ? getResources().getColor(R.color.gray) : getResources().getColor(R.color.blue));
                            signInView.setText(signIn ? Constant.SIGNED_IN : Constant.SIGN_IN);
                            if (!signIn) {
                                signInView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        signIn();
                                    }
                                });
                            }
                            qianDaoDays = userDetail.getQianDaoDays();
                            qianDaoDaysView.setText("连续签到" + qianDaoDays + "天");

                        }
                    });
                }

            }
        }).start();
    }

    private void signIn() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.SIGN_IN), token.getToken());
                if (!Constant.RESPONSE_BADLY.equals(result)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pointView.setText(Constant.POINT + (currentPoint + 10));
                            qianDaoDaysView.setText("连续签到" + (qianDaoDays + 1) + "天");
                            signInView.setText(Constant.SIGNED_IN);
                            signInView.setTextColor(getResources().getColor(R.color.gray));
                            signInView.setOnClickListener(null);
                            Toast.makeText(getActivity(), getString(R.string.sign_in), Toast.LENGTH_SHORT).show();

                        }
                    });
                }
            }
        }).start();
    }


    private void loadNews(final boolean loadNewest) {
        final boolean loadHistory = !loadNewest;
        if (loadNewest) {
            updateTo = "";
            news.clear();
        } else {
            if (!news.isEmpty()) {
                updateTo = news.getLast().getCreatedDateTime();
            }
        }

        final String finalUpdateTo = updateTo;
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("loadNewest", loadNewest);
                    paramJson.put("loadHistory", loadHistory);
                    paramJson.put("updateTo", finalUpdateTo);
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                    final String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.NEWS), token.getToken(), paramEntity);

                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jsonObject = new JSONObject(result);
                                    JSONArray newsArray = jsonObject.getJSONArray("newsList");
                                    String guid, title, body, createdDateTime;
                                    for (int i = 0; i < newsArray.length(); i++) {
                                        JSONObject newObj = newsArray.getJSONObject(i);
                                        guid = newObj.getString("guid");
                                        title = newObj.getString("title");
                                        body = newObj.getString("body");
                                        createdDateTime = newObj.getString("createdDateTime");
                                        News newsItem = new News(guid, title, body, createdDateTime);
                                        if (loadNewest) {
                                            news.add(newsItem);
                                        } else {
                                            news.addLast(newsItem);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                newsAdapter.notifyDataSetChanged();
                                newsListView.onRefreshComplete();

//                                if (loadNewest) {
//                                    newsView.onRefreshComplete();
//                                } else {
//                                    newsView.onLoadMoreComplete();
//                                }

                            }
                        });

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private class NewsAdapter extends BaseAdapter {

        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private NewsViewCache viewCache;

        private NewsAdapter(Context context, int resource) {
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return news.size();
        }

        @Override
        public Object getItem(int position) {
            return news.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            TextView contentView, createTimeView;
            if (convertView == null) {//第一次渲染
                convertView = inflater.inflate(resource, null);
                contentView = (TextView) convertView.findViewById(R.id.content);
                createTimeView = (TextView) convertView.findViewById(R.id.create_datetime);
                viewCache = new NewsViewCache();
                viewCache.contentView = contentView;
                viewCache.createTimeView = createTimeView;
                convertView.setTag(viewCache);
            } else {
                viewCache = (NewsViewCache) convertView.getTag();
                contentView = viewCache.contentView;
                createTimeView = viewCache.createTimeView;
            }
            convertView.getBackground().setAlpha(50);

            News newsItem = news.get(position);

            contentView.setText(newsItem.getTitle());
            createTimeView.setText(newsItem.getCreatedDateTime());

            return convertView;
        }

        private class NewsViewCache {
            private TextView contentView;
            private TextView createTimeView;

        }
    }

}
